package com.example.print.fragment;


import android.Manifest;
//import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.print.R;
import com.example.print.activity.MainActivity;
import com.panling.printapi.MdUtils;
import java.io.File;

/**
 * A simple {@link Fragment} subclass.
 */
public class PrintPictureFragment extends Fragment implements View.OnClickListener{
    protected String TAG = "PrintPictureActivity";

    private static final int REQUEST_CODE_READ_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_CODE_CAMERA = 2;
    private static final int REQUEST_CODE_PICK_IMAGE = 3;
    private static final int REQUEST_CODE_CAMERA_CAPTURE = 4;
    private static final int REQUEST_CODE_CAMERA_ZOOM = 5;

    private LinearLayout pictureadd, camerepicture;
    private Button btn_pictureprint;
    private ImageView img_codes;
    private EditText et_hint, Pic_Paper_distance, Pic_chroma;
    private Bitmap bitmap;
    private int p_distance, p_chroma;

    private int choose = 0;
    private MainActivity mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_printpicture, container, false);
    }

   // @SuppressLint("ResourceType")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mContext = (MainActivity) getActivity();

        pictureadd = mContext.findViewById(R.id.pictureadd);
        camerepicture = mContext.findViewById(R.id.camerepicture);
        img_codes = mContext.findViewById(R.id.img_codes);
        btn_pictureprint = mContext.findViewById(R.id.btn_pictureprint);
        //走纸距离及浓度
        Pic_Paper_distance = mContext.findViewById(R.id.Pic_Paper_distance);
        Pic_chroma = mContext.findViewById(R.id.Pic_chroma);

        img_codes.setImageDrawable(getResources().getDrawable((R.mipmap.printimg111)));
        pictureadd.setOnClickListener(this);
        camerepicture.setOnClickListener(this);

        //照片打印监听事件,功能暂未实现
        btn_pictureprint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String paper_dis = Pic_Paper_distance.getText().toString().trim();
                String chroma = Pic_chroma.getText().toString().trim();

                if(false == mContext.IsPrinterNormal() || mContext.get_is_printing())
                {
                    Toast.makeText(mContext, R.string.PrintBusy, Toast.LENGTH_SHORT).show();
                    return;
                }
                mContext.set_is_printing(true);
                try {
                    p_distance = Integer.parseInt(paper_dis);
                    p_chroma = Integer.parseInt(chroma);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mContext.mPrinter.setPrintChromaLevel(p_chroma);
                mContext.mPrinter.setPrintAlignmentMode(1);

                Log.e(TAG, "btn_pictureprint...choose=" + choose);
                if (choose == 0) {
                    try {
                        bitmap = BitmapFactory.decodeStream(getResources().getAssets().open("printimg111.jpg"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    bitmap = PrintBmp;
                }

                Log.e(TAG, "btn_pictureprint...getWidth=" + bitmap.getWidth() + ", getHeight=" + bitmap.getHeight());
               // mContext.mPrinter.printImage(bitmap);
                new Thread() {
                    @Override
                    public void run() {
                if (mContext.mPrinter.blacklabel_status){
                    mContext.mPrinter.printImage3(bitmap, 100);
                    //跳转到下一张标签同样的位置
                    mContext.mPrinter.Feed_to_Next();
                }else {
                            mContext.mPrinter.printImage3(bitmap, 6);
                }
                img_codes.setDrawingCacheEnabled(false);
                //打印完走纸设置的行数
                mContext.mPrinter.setFeedRow(0, p_distance);
                    }
                }.start();
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                mContext.set_is_printing(false);
            }
        });
    }

    //相机与相册点击监听事件
    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.pictureadd:
                    //Toast.makeText(mContext.getBaseContext(), "暂不开放！", Toast.LENGTH_SHORT).show();
                    if (ContextCompat.checkSelfPermission(mContext.getBaseContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 未获取权限，向用户请求读取外部存储器的权限
                        ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_READ_EXTERNAL_STORAGE);
                    } else {
                        // 已获取权限，打开相册
                        openGallery();
                    }
                    break;
                case R.id.camerepicture:
                    Toast.makeText(mContext.getBaseContext(), R.string.Not_currently_open, Toast.LENGTH_SHORT).show();
//                    if (ContextCompat.checkSelfPermission(mContext.getBaseContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                        // 未获取权限，向用户请求相机的权限
//                        ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
//                    } else {
//                        // 已获取权限，打开相机
//                        openCamera();
//                    }
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 相机权限或去方法
     *
     * @param requestCode(android.app.Activity,String[],int)}
     * @param permissions                                     The requested permissions. Never null.
     * @param grantResults                                    The grant results for the corresponding permissions
     *                                                        which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
     *                                                        or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了读取外部存储器的权限，打开相册
                openGallery();
            } else {
                // 用户拒绝了读取外部存储器的权限，可以进行更改提示内容
                Toast.makeText(mContext, R.string.Album_authorize, Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_CODE_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了相机的权限，打开相机
                openCamera();
            } else {
                // 用户拒绝了相机的权限，可以进行更改提示内容
                Toast.makeText(mContext, R.string.Camera_authorize, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //打开相册方法
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    //打开相机方法
    private void openCamera() {
        File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(mContext, null);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(externalFilesDirs[0], getPhotoName());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, REQUEST_CODE_CAMERA_CAPTURE);
    }

    private void startPhotoZoom(Uri data, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        // crop为true时表示显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CAMERA_ZOOM);
    }

    private Bitmap PrintBmp ;
    private File file;
    //拍照上传逻辑
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int dw = mContext.getWindowManager().getDefaultDisplay().getWidth();
        int dh = mContext.getWindowManager().getDefaultDisplay().getHeight() / 2;

        if (resultCode == mContext.RESULT_OK) {
            if (requestCode == REQUEST_CODE_PICK_IMAGE && data != null) {
                choose = 1;
                Uri selectedImageUri = data.getData();
                //img_code.setImageURI(selectedImageUri);
                try {
                    BitmapFactory.Options factory = new BitmapFactory.Options();
                    factory.inJustDecodeBounds = true; //当为true时  允许查询图片不为 图片像素分配内存
                    Bitmap bmp = BitmapFactory.decodeStream(mContext.getContentResolver()
                            .openInputStream(selectedImageUri), null, factory);
                    int hRatio = (int) Math.ceil(factory.outHeight / (float) dh); //图片是高度的几倍
                    int wRatio = (int) Math.ceil(factory.outWidth / (float) dw); //图片是宽度的几倍
                    //System.out.println("hRatio:" + hRatio + "  wRatio:" + wRatio);
                    Log.e(TAG, "ImageBitmap hRatio:" + hRatio + "  wRatio:" + wRatio);
                    //缩小到  1/ratio的尺寸和 1/ratio^2的像素
                    if (hRatio > 1 || wRatio > 1) {
                        if (hRatio > wRatio) {
                            factory.inSampleSize = hRatio;
                        } else
                            factory.inSampleSize = wRatio;
                    }
                    factory.inJustDecodeBounds = false;
                    bmp = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(selectedImageUri), null, factory);
                    PrintBmp = com.panling.printapi.MdUtils.convertToBlackAndWhite(bmp);// 进行黑白处理
                    Log.e(TAG, "ImageBitmap...getWidth=" + PrintBmp.getWidth() + ", getHeight=" + PrintBmp.getHeight());
                    img_codes.setImageBitmap(PrintBmp);
                } catch (Exception ex) {
                }

            } else if (requestCode == REQUEST_CODE_CAMERA_CAPTURE && data != null) {
                Bitmap Picture = (Bitmap) data.getExtras().get("data");
                PrintBmp = com.panling.printapi.MdUtils.convertToBlackAndWhite(Picture);// 进行黑白处理
                img_codes.setImageBitmap(PrintBmp);

                //Uri uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID.concat(".provider"), file);
                //startPhotoZoom(uri, 300);
            } else if (requestCode == REQUEST_CODE_CAMERA_ZOOM && data != null) {
                Bundle bundle = data.getExtras();
                Log.e(TAG, "ImageBitmap...bundle=" + bundle);
                if (bundle != null) {
                    Bitmap bitmap = bundle.getParcelable("data");
                    PrintBmp = com.panling.printapi.MdUtils.convertToBlackAndWhite(bitmap);
                    img_codes.setImageBitmap(PrintBmp);
                    //img_codes.setBackgroundDrawable(new BitmapDrawable(PrintBmp));
                }
            }
        }
    }

    private String getPhotoName() {
        String name = System.currentTimeMillis() + ".jpg";
        return name;
    }

}
